#include <stdio.h>
#include <windows.h>
#include "MySQL.h"

MySQL::MySQL(void)
{
}

MySQL::~MySQL(void)
{
	Release();
	Close();
}

bool MySQL::Connect(const char *pHost,const char *pUser,
		const char *pPassword, const char *pDatabase,
		unsigned int nPort,const char *pChrSet)
{
	try
	{
		m_pMySQL = mysql_init(NULL);
		if (mysql_real_connect(m_pMySQL, pHost, pUser, pPassword,
			pDatabase, nPort, NULL, 0) == NULL)
		{
			return false;
		}
		if(pChrSet != NULL)
		{
			mysql_set_character_set(m_pMySQL,pChrSet);
		}
		return true;
	}
	catch(...)
	{
		printf(mysql_error(m_pMySQL));
		Close();
		return false;
	}
}

void MySQL::Close(void)
{
	Release();
	if (m_pMySQL != NULL)
	{
		mysql_close(m_pMySQL);
	}
}

int MySQL::SelectDb(const char *db)
{
	return mysql_select_db(m_pMySQL,db);
}

const char* MySQL::GetCharacter(void)
{
	return mysql_character_set_name(m_pMySQL);
}

int MySQL::Query(const char *sql)
{
	int result = mysql_query(m_pMySQL, sql);
	m_pRes = mysql_store_result(m_pMySQL);

	return result;
}

int MySQL::Execute(const char *sql)
{
	int result;
	try
	{
		result = mysql_real_query(m_pMySQL, sql, (unsigned long)strlen(sql));
		return result;
	}
	catch(...)
	{
		printf(mysql_error(m_pMySQL));
		Close();
		return false;
	}
}

void MySQL::Release(void)
{
	if (m_pRes != NULL)
	{
		mysql_free_result(m_pRes);
	}
}

bool MySQL::IsBeginBOF(void)
{
	return false;
}

bool MySQL::IsEndEOF(void)
{
	MyRow = mysql_fetch_row(m_pRes);
	if(MyRow)
		return false;
	return true;
}

char * MySQL::GetField(int nIndex)
{
	return MyRow[nIndex];
}

void MySQL::GetField(int nIndex,char * strValue)
{
	strValue = MyRow[nIndex];
}
